package com.cloud.point.concurrent.disruptor;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;

import java.nio.ByteBuffer;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import net.openhft.affinity.AffinityThreadFactory;

/**
 * disruptor使用实例
 *
 * @author 24373
 * @version 1.0
 * @date 2024-06-27 22:37
 */
public class TestDisruptor {

    public static void main(String[] args) {
        AffinityThreadFactory affinityThreadFactory = new AffinityThreadFactory("aft-handler");
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        LongEventFactory factory = new LongEventFactory();
        int ringBufferSize = 2 << 5;

        Disruptor<LongEvent> disruptor = new Disruptor<>(
                // 事件生产工厂
                factory,
                // 事件工厂大小 必须2的次方
                ringBufferSize,
                // 事件执行线程工厂
                threadFactory,
                //executor,
                // 声明策略
                ProducerType.SINGLE,
                // 等待策略
                new YieldingWaitStrategy()
        );
        // 连接消费端方法
        disruptor.handleEventsWith(new EventHandler[]{new LongEventHandler(), new LongEventHandler2()});
        disruptor.start();
        // 创建RingBuffer容器
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
        LongEventProducer producer = new LongEventProducer(ringBuffer);
        ByteBuffer byteBuffer = ByteBuffer.allocate(8);
        for (int i = 0; i < 100; i++) {
            byteBuffer.putLong(0, i);
            producer.onData(byteBuffer);
        }
        disruptor.shutdown();

    }

}

